package com.bhs.sansonglogistics.ui.consumptionCoupon;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseBean;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.bean.CouponBean;
import com.bhs.sansonglogistics.bean.CouponList;
import com.bhs.sansonglogistics.bean.event.CouponRefresh;
import com.bhs.sansonglogistics.bean.event.OrderEvent;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.CouponAdapter;
import com.bhs.sansonglogistics.ui.waybill.UpstreamShipmentListFragment;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 券列表
 */
public class CouponListFragment extends BaseFragment implements View.OnClickListener, NetCallBack {

    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRvList;

    private CouponAdapter mAdapter;
    private int page=1;
    private int type;
    private int removeId;

    public static CouponListFragment newInstance(int type) {
        CouponListFragment fragment = new CouponListFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int initLayout() {
        return R.layout.fragment_coupon;
    }

    @Override
    public void initView(View root) {
        //注册监听
        EventBus.getDefault().register(this);
        mRefreshLayout = root.findViewById(R.id.refreshLayout);
        mRvList = root.findViewById(R.id.rv_list);
        root.findViewById(R.id.btn_submit).setOnClickListener(this);
        type = getArguments().getInt("type");
        mAdapter = new CouponAdapter(type);

    }

    @Override
    public void initData() {
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter.setEmptyView(LayoutInflater.from(getContext()).inflate(R.layout.layout_empty, null));

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CouponBean info = mAdapter.getData().get(position);
                int couponId = info.getId();
                if (view.getId() == R.id.tv_specification) {
                    startActivity(new Intent(getActivity(), CouponDetailActivity.class)
                            .putExtra("couponId", couponId)
                            .putExtra("takeNum",info.getTakeNum())
                            .putExtra("usedNum",info.getUsedNum())
                            .putExtra("passedNum",info.getPassed_num()));
                } else if (view.getId() == R.id.tv_over) {
                    new XPopup.Builder(getActivity())
                            .asConfirm("提示", "确认结束吗？",
                                    "取消", "确定",
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            loadingPopupShow();
                                            removeId = position;
                                            networkRequest(netApi.endCoupon(couponId), CouponListFragment.this, 777);
                                        }
                                    }, null, false)
                            .show();
                }
            }
        });

        //监听 刷新是回调
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData();
            }
        });
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                loadData();
            }
        }, mRvList);

        loadData();
    }

    private void loadData() {
        networkRequest(netApi.couponList(page, 10, type,0), this, 666);
    }

    @Override
    public void onClick(View view) {
        startActivity(new Intent(getContext(), IssueCouponsActivity.class));
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 666) {
            mRefreshLayout.setRefreshing(false);
            CouponList couponList = new Gson().fromJson(json, CouponList.class);
            if (couponList.isStatus()) {
                if (page == 1) {
                    mAdapter.setNewData(couponList.getData().getList());
                } else {
                    mAdapter.loadMoreComplete();
                    mAdapter.addData(couponList.getData().getList());
                }
                if (mAdapter.getData().size() >= couponList.getData().getTotal_count()) {
                    mAdapter.loadMoreEnd();
                }
            } else {
                ToastUtil.show(couponList.getMsg());
            }
        } else if (requestCode == 777) {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.isStatus()) {
                mAdapter.remove(removeId);
                EventBus.getDefault().post(new CouponRefresh(2));
                loadingPopupDismiss();
            } else {
                ToastUtil.show(bean.getMsg());
            }
        }
    }

    @Subscribe
    public void onEvent(CouponRefresh event) {
        if (event.getType() == type) {
            page = 1;
            loadData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onFailure(int requestCode) {
        mRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
        loadingPopupDismiss();
    }
}